package web.suzy.oj.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * YangSuzy 软件工作室
 * 类名: IpUtils
 * 描述: ---- 待定 -----
 * 功能: ---- 待定 -----
 *
 * @author YangSuzy
 * Date: 2022/11/13 21:50
 */
@Slf4j(topic = "suzyoj")
public class IpUtils {
    /**
     * 方法名: getUserIpAddr
     * 描述: 获取用户IP
     *
     * @param request
     * @return java.lang.String
     * @date 2022/11/13 21:50
     * @auther YangSuzy
     **/
    public static String getUserIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    try {
                        ipAddress = InetAddress.getLocalHost().getHostAddress();
                    } catch (UnknownHostException e) {
                        log.error("用户ip获取异常------->{}", e.getMessage());
                    }
                }
            }
            //通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null) {
                if (ipAddress.contains(",")) {
                    return ipAddress.split(",")[0];
                }
                return ipAddress;
            }
            return "";
        } catch (Exception e) {
            log.error("用户ip获取异常------->{}", e.getMessage());
            return "";
        }
    }

    /**
     * 方法名: getServiceIp
     * 描述: 获取主机 IP
     *
     * @return java.lang.String
     * @date 2022/11/13 21:51
     * @auther YangSuzy
     **/
    public static String getServiceIp() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
            //返回IP地址
            return address.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("本地ip获取异常---------->{}", e.getMessage());
        }
        return null;
    }
}
